<template>
  <view class="container">

    <!-- 页面内容 -->
    <view class="content">
      <!-- 用户信息 -->
      

      <!-- 二维码区域 -->
      <view class="qrcode-section">
        <view class="user-section">
        <view class="user-info-horizontal">
          <image class="user-avatar" :src="userInfo.avatarUrl" mode="aspectFill"></image>
          <view class="user-details">
            <text class="user-name">{{ userInfo.name }}</text>
            <text class="user-phone">{{ userInfo.phone }}</text>
          </view>
        </view>
      </view>
        <view class="qrcode-container">
          <image class="qrcode-image" :src="qrcodeUrl" mode="aspectFit"></image>
        </view>
      </view>

    </view>
      <!-- 保存按钮 -->
      <view class="save-section">
        <button class="save-btn" @click="saveImage">保存图片</button>
      </view>
      
      <!-- 隐藏的 canvas 用于生成图片 -->
      <canvas 
        canvas-id="shareCanvas" 
        :style="{ width: canvasWidth + 'px', height: canvasHeight + 'px', position: 'fixed', left: '-9999px', top: '-9999px' }"
      ></canvas>
  </view>
</template>

<script>
import authManager from '@/utils/auth';
import { userApi } from '@/request/user';

export default {
  data() {
    return {
      statusBarHeight: 0,
      navbarHeight: 0,
      userInfo: {
        avatar: '',
        name: '',
        phone: ''
      },
      qrcodeUrl: '',
      canvasWidth: 375,
      canvasHeight: 600,
      ctx: null
    }
  },
  onLoad() {
    this.initPage();
    this.getUserInfo();
    this.generateQRCode();
    this.initCanvas();
  },
  methods: {
    initPage() {
      const systemInfo = uni.getSystemInfoSync();
      this.statusBarHeight = systemInfo.statusBarHeight;
      this.navbarHeight = this.statusBarHeight + uni.upx2px(88);
    },
    
    initCanvas() {
      this.ctx = uni.createCanvasContext('shareCanvas', this);
    },
    
    goBack() {
      uni.navigateBack();
    },
    
    showMore() {
      uni.showActionSheet({
        itemList: ['分享给朋友', '发送给朋友'],
        success: (res) => {
          if (res.tapIndex === 0) {
            this.shareToFriend();
          } else if (res.tapIndex === 1) {
            this.shareToChat();
          }
        }
      });
    },
    
    async getUserInfo() {
      try {
        this.userInfo = authManager.getUserInfo();
      } catch (error) {
        console.error('获取用户信息失败:', error);
      }
    },
    
    generateQRCode() {
      // 生成二维码，这里需要根据实际需求调用相应的API
      // 临时使用示例二维码
      userApi.getQrCode({
        page: 'pages/index/index',
      }).then(res => {
        this.qrcodeUrl = res;
      })
    },
    
    async saveImage() {
      uni.showLoading({
        title: '生成中...'
      });
      
      try {
        // 如果二维码是 base64 格式，直接使用截图方式
        if (this.qrcodeUrl && !this.qrcodeUrl.startsWith('http')) {
          await this.captureScreenshot();
        } else {
          await this.generateShareImage();
        }
      } catch (error) {
        console.error('生成图片失败:', error);
        uni.hideLoading();
        uni.showToast({
          title: '生成图片失败',
          icon: 'none'
        });
      }
    },
    
    captureScreenshot() {
      return new Promise((resolve, reject) => {
        // 使用页面截图的方式
        const query = uni.createSelectorQuery().in(this);
        query.select('.content').boundingClientRect((rect) => {
          if (rect) {
            // 创建 canvas 上下文
            if (!this.ctx) {
              this.initCanvas();
            }
            
            // 设置 canvas 尺寸
            const canvasWidth = rect.width;
            const canvasHeight = rect.height;
            
            // 设置背景
            this.ctx.fillStyle = '#ffffff';
            this.ctx.fillRect(0, 0, canvasWidth, canvasHeight);
            
            // 绘制用户信息和二维码
            this.drawContentToCanvas(canvasWidth, canvasHeight).then(() => {
              resolve();
            }).catch(reject);
          } else {
            reject(new Error('无法获取页面元素信息'));
          }
        }).exec();
      });
    },
    
    async drawContentToCanvas(canvasWidth, canvasHeight) {
      try {
        // 获取头像信息
        const avatarInfo = await this.getImageInfo(this.userInfo.avatar || 'https://jyoungy.oss-cn-beijing.aliyuncs.com/jyy-mini-sale/login/logo.png');
        
        // 绘制用户头像
        const avatarSize = uni.upx2px(120);
        const avatarX = uni.upx2px(120);
        const avatarY = uni.upx2px(80);
        
        // 绘制圆形头像
        this.ctx.save();
        this.ctx.beginPath();
        this.ctx.arc(avatarX + avatarSize/2, avatarY + avatarSize/2, avatarSize/2, 0, 2 * Math.PI);
        this.ctx.clip();
        this.ctx.drawImage(avatarInfo.path, avatarX, avatarY, avatarSize, avatarSize);
        this.ctx.restore();
        
        // 绘制用户名
        this.ctx.fillStyle = '#000000';
        this.ctx.font = `${uni.upx2px(38)}px Arial`;
        this.ctx.fillText(this.userInfo.name, avatarX + avatarSize + uni.upx2px(30), avatarY + uni.upx2px(30));
        
        // 绘制手机号
        this.ctx.fillStyle = '#999999';
        this.ctx.font = `${uni.upx2px(28)}px Arial`;
        this.ctx.fillText(this.userInfo.phone, avatarX + avatarSize + uni.upx2px(30), avatarY + uni.upx2px(65));
        
        // 处理二维码 - 使用新的方法
        await this.drawBase64QRCode();
        
      } catch (error) {
        console.error('绘制内容失败:', error);
        throw error;
      }
    },
    
    drawBase64QRCode() {
      return new Promise(async (resolve, reject) => {
        if (!this.qrcodeUrl) {
          reject(new Error('二维码数据为空'));
          return;
        }
        
        try {
          // 将 base64 转换为临时文件
          const tempFilePath = await this.convertBase64ToTempFile(this.qrcodeUrl);
          
          // 使用临时文件路径绘制二维码
          const qrcodeSize = uni.upx2px(500);
          const qrcodeX = (this.canvasWidth - qrcodeSize) / 2;
          const qrcodeY = uni.upx2px(400);
          
          // 直接使用文件路径绘制
          this.ctx.drawImage(tempFilePath, qrcodeX, qrcodeY, qrcodeSize, qrcodeSize);
          
          // 执行绘制
          this.ctx.draw(false, () => {
            setTimeout(() => {
              // 将 canvas 转换为图片
              uni.canvasToTempFilePath({
                canvasId: 'shareCanvas',
                success: (res) => {
                  // 保存到相册
                  uni.saveImageToPhotosAlbum({
                    filePath: res.tempFilePath,
                    success: () => {
                      uni.hideLoading();
                      uni.showToast({
                        title: '保存成功',
                        icon: 'success'
                      });
                      resolve();
                    },
                    fail: (error) => {
                      uni.hideLoading();
                      if (error.errMsg.includes('deny')) {
                        uni.showModal({
                          title: '提示',
                          content: '需要您授权保存图片到相册',
                          showCancel: false
                        });
                      } else {
                        uni.showToast({
                          title: '保存失败',
                          icon: 'none'
                        });
                      }
                      resolve();
                    }
                  });
                },
                fail: (error) => {
                  uni.hideLoading();
                  console.error('canvas转图片失败:', error);
                  uni.showToast({
                    title: '生成图片失败',
                    icon: 'none'
                  });
                  reject(error);
                }
              }, this);
            }, 500);
          });
          
        } catch (error) {
          console.error('绘制二维码失败:', error);
          // 如果转换失败，使用备用方案
          this.fallbackDrawQRCode().then(resolve).catch(reject);
        }
      });
    },
    
    fallbackDrawQRCode() {
      return new Promise((resolve, reject) => {
        // 备用方案：直接绘制一个占位符
        const qrcodeSize = uni.upx2px(500);
        const qrcodeX = (this.canvasWidth - qrcodeSize) / 2;
        const qrcodeY = uni.upx2px(400);
        
        // 绘制二维码边框
        this.ctx.strokeStyle = '#000000';
        this.ctx.lineWidth = 2;
        this.ctx.strokeRect(qrcodeX, qrcodeY, qrcodeSize, qrcodeSize);
        
        // 绘制提示文字
        this.ctx.fillStyle = '#666666';
        this.ctx.font = `${uni.upx2px(24)}px Arial`;
        this.ctx.textAlign = 'center';
        this.ctx.fillText('二维码', qrcodeX + qrcodeSize/2, qrcodeY + qrcodeSize/2);
        
        // 执行绘制
        this.ctx.draw(false, () => {
          setTimeout(() => {
            // 将 canvas 转换为图片
            uni.canvasToTempFilePath({
              canvasId: 'shareCanvas',
        success: (res) => {
            // 保存到相册
            uni.saveImageToPhotosAlbum({
              filePath: res.tempFilePath,
              success: () => {
                uni.hideLoading();
                uni.showToast({
                  title: '保存成功',
                  icon: 'success'
                });
                    resolve();
              },
              fail: (error) => {
                uni.hideLoading();
                if (error.errMsg.includes('deny')) {
                  uni.showModal({
                    title: '提示',
                    content: '需要您授权保存图片到相册',
                    showCancel: false
                  });
                } else {
                  uni.showToast({
                    title: '保存失败',
                    icon: 'none'
                  });
                }
                    resolve();
                  }
                });
              },
              fail: (error) => {
                uni.hideLoading();
                console.error('canvas转图片失败:', error);
                uni.showToast({
                  title: '生成图片失败',
                  icon: 'none'
                });
                reject(error);
              }
            }, this);
          }, 500);
        });
      });
    },
    
    async generateShareImage() {
      if (!this.ctx) {
        this.initCanvas();
      }
      
      // 设置背景
      this.ctx.fillStyle = '#ffffff';
      this.ctx.fillRect(0, 0, this.canvasWidth, this.canvasHeight);
      
      try {
        // 获取头像信息
        const avatarInfo = await this.getImageInfo(this.userInfo.avatar || 'https://jyoungy.oss-cn-beijing.aliyuncs.com/jyy-mini-sale/login/logo.png');
        
        // 绘制用户头像
        const avatarSize = 60;
        const avatarX = 60;
        const avatarY = 80;
        
        // 绘制圆形头像
        this.ctx.save();
        this.ctx.beginPath();
        this.ctx.arc(avatarX + avatarSize/2, avatarY + avatarSize/2, avatarSize/2, 0, 2 * Math.PI);
        this.ctx.clip();
        this.ctx.drawImage(avatarInfo.path, avatarX, avatarY, avatarSize, avatarSize);
        this.ctx.restore();
        
        // 绘制用户名
        this.ctx.fillStyle = '#000000';
        this.ctx.font = '18px Arial';
        this.ctx.fillText(this.userInfo.name, avatarX + avatarSize + 15, avatarY + 20);
        
        // 绘制手机号
        this.ctx.fillStyle = '#999999';
        this.ctx.font = '14px Arial';
        this.ctx.fillText('123123' + this.userInfo.phone, avatarX + avatarSize + 15, avatarY + 45);
        
        // 处理二维码 - 直接使用 base64 数据
        await this.drawQRCodeToCanvas();
        
      } catch (error) {
        console.error('绘制图片失败:', error);
        throw error;
      }
    },
    
    drawQRCodeToCanvas() {
      return new Promise(async (resolve, reject) => {
        if (!this.qrcodeUrl) {
          reject(new Error('二维码数据为空'));
          return;
        }
        
        try {
          let imagePath = this.qrcodeUrl;
          
          // 如果是 base64 数据，需要先转换为临时文件
          if (!this.qrcodeUrl.startsWith('http')) {
            imagePath = await this.convertBase64ToTempFile(this.qrcodeUrl);
          }
          
          // 获取图片信息
          const imageInfo = await this.getImageInfo(imagePath);
          
          // 绘制二维码
          const qrcodeSize = 250;
          const qrcodeX = (this.canvasWidth - qrcodeSize) / 2;
          const qrcodeY = 200;
          
          this.ctx.drawImage(imageInfo.path, qrcodeX, qrcodeY, qrcodeSize, qrcodeSize);
          
          // 执行绘制
          this.ctx.draw(false, () => {
            setTimeout(() => {
              // 将 canvas 转换为图片
              uni.canvasToTempFilePath({
                canvasId: 'shareCanvas',
                success: (res) => {
                  // 保存到相册
                  uni.saveImageToPhotosAlbum({
                    filePath: res.tempFilePath,
                    success: () => {
          uni.hideLoading();
          uni.showToast({
                        title: '保存成功',
                        icon: 'success'
                      });
                      resolve();
                    },
                    fail: (error) => {
                      uni.hideLoading();
                      if (error.errMsg.includes('deny')) {
                        uni.showModal({
                          title: '提示',
                          content: '需要您授权保存图片到相册',
                          showCancel: false
                        });
                      } else {
                        uni.showToast({
                          title: '保存失败',
                          icon: 'none'
                        });
                      }
                      resolve();
                    }
                  });
                },
                fail: (error) => {
                  uni.hideLoading();
                  console.error('canvas转图片失败:', error);
                  uni.showToast({
                    title: '生成图片失败',
            icon: 'none'
                  });
                  reject(error);
                }
              }, this);
            }, 500);
          });
          
        } catch (error) {
          console.error('绘制二维码失败:', error);
          reject(error);
        }
      });
    },
    
    convertBase64ToTempFile(base64Data) {
      return new Promise((resolve, reject) => {
        try {
          // 确保 base64 数据格式正确
          let base64String = base64Data;
          if (!base64String.startsWith('data:image')) {
            base64String = `data:image/png;base64,${base64String}`;
          }
          
          // 提取纯 base64 编码部分
          const base64 = base64String.split(',')[1];
          
          // 使用 uni.base64ToArrayBuffer 转换为 ArrayBuffer
          const buffer = uni.base64ToArrayBuffer(base64);
          
          // 获取文件系统管理器的实例
          const fsm = uni.getFileSystemManager();
          
          // 生成临时文件路径
          const fileName = `${wx.env.USER_DATA_PATH}/share_img_${Date.now()}.png`;
          
          console.log('准备写入文件:', fileName);
          
          // 写入文件，使用 binary 编码
          fsm.writeFile({
            filePath: fileName,
            data: buffer,
            encoding: 'binary',
            success: () => {
              console.log('base64转换成功:', fileName);
              resolve(fileName);
            },
            fail: (error) => {
              console.error('文件保存失败:', error);
              reject(error);
            }
          });
          
        } catch (error) {
          console.error('base64ToArrayBuffer转换失败:', error);
          reject(error);
        }
      });
    },
    
    getImageInfo(src) {
      return new Promise((resolve, reject) => {
        uni.getImageInfo({
          src: src,
          success: (res) => {
            resolve(res);
          },
          fail: (error) => {
            reject(error);
          }
        });
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background-color: #fff;
  position: relative;
}

.content {
  padding: 0 120rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  height: 100vh;
}

.user-section {
  display: flex;
  flex-direction: column;
  width: 100%;
  align-items: flex-start;
  margin-bottom: 40rpx;
  
  .user-info-horizontal {
    display: flex;
    align-items: center;
    
    .user-details {
      display: flex;
      flex-direction: column;
      margin-left: 30rpx;
    }
  }
  
  .user-avatar {
    width: 120rpx;
    height: 120rpx;
    border-radius: 60rpx;
    border: 4rpx solid #ffffff;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  }
  
  .user-name {
    font-size: 38rpx;
    font-weight: 600;
    color: #000;
    margin-bottom: 20rpx;
  }
  
  .user-phone {
    font-size: 28rpx;
    color: #999;
  }
}

.qrcode-section {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  margin-bottom: 80rpx;
  
  .qrcode-container {
    position: relative;
    width: 500rpx;
    height: 500rpx;
    background-color: #ffffff;
    border-radius: 20rpx;
    padding: 40rpx;
    // box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.1);
    
    .qrcode-image {
      width: 100%;
      height: 100%;
    }
    
    .wechat-logo {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      width: 80rpx;
      height: 80rpx;
      background-color: #000000;
      border-radius: 16rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      
      image {
        width: 50rpx;
        height: 50rpx;
      }
    }
  }
}

.save-section {
  width: 100%;
  position: fixed;
  bottom: 88rpx;
  left: 0;
  right: 0;
  background-color: #ffffff;
  
  .save-btn {
    width: 298rpx;
    height: 66rpx;
    line-height: 66rpx;
    background-color: #000000;
    color: #ffffff;
    font-size: 24rpx;
    border-radius: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    
    &::after {
      border: none;
    }
    
  }
}
</style>
